<template>
  <div>
    <!-- 功能按钮 -->
    <el-form class="tableSearch" size="mini">
      <el-form-item>
        <el-button type="primary" @click="$router.back(-1)">返回</el-button>
        <el-button type="primary" v-if="setRole('修改')" v-show="showTab == '1' && canEdit == true" @click="handleEdit()">修改</el-button>
        <el-button type="primary" v-show="showTab == '2'" @click="submitForm('formdata')">保存</el-button>
        <el-button type="primary" v-if="setRole('关闭报货单')" v-show="showTab == '1' && canClose == true" @click="handleOrderDeal(7)">关闭单据</el-button>
        <el-button type="primary" v-if="setRole('取消报货单')" v-show="showTab == '1' && canCancel == true" @click="handleOrderDeal(4)">取消单据</el-button>
        <el-button type="primary" v-show="showTab == '2'" @click="openGoodsdialog()">批量添加商品</el-button>
        <el-button type="primary" v-show="showTab == '2'" @click="selectTable.handleMultipleDel()">批量删除商品</el-button>
      </el-form-item>
    </el-form>

    <!-- form表单 -->
    <el-form :model="formdata" :rules="rules" ref="formdata" label-width="120px" size="mini">
      <el-row>
        <el-col :span="8">
          <el-form-item label="收货日期：" prop="receiveDate">
            <span v-show="showTab == '1'">{{formdata.receiveDate}}</span>
            <el-date-picker v-show="showTab == '2'" v-model="formdata.receivseDate" format="yyyy年 MM 月 dd 日" value-format="yyyy-MM-dd" type="date" placeholder="选择收货日期"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="订单状态：">
            <span v-show="showTab == '1'">{{orderStatusArr[formdata.statusFlow]}}</span>
            <el-input v-show="showTab == '2'" v-model="orderStatusArr[formdata.statusFlow]" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
      <el-row>
        <el-col :span="8">
          <el-form-item label="单据日期：">
            <span v-show="showTab == '1'">{{formdata.orderDate}}</span>
            <el-date-picker v-show="showTab == '2'" v-model="formdata.orderDate" format="yyyy年 MM 月 dd 日" value-format="yyyy-MM-dd" type="date" disabled :formatter="timestamp"></el-date-picker>
          </el-form-item>
        </el-col>
        <el-col :span="8">
          <el-form-item label="单据编号：">
            <span v-show="showTab == '1'">{{formdata.purchaseCode}}</span>
            <el-input v-show="showTab == '2'" v-model="formdata.purchaseCode" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 表格 -->
    <el-table :data="selectTable.tableData" @selection-change="selectTable.handleMultipleSelect">
      <el-table-column type="selection" width="55" align="center"></el-table-column>
      <el-table-column type="index" label="#" width="55"></el-table-column>
      <el-table-column prop="goodsCode" label="商品货号" align="center"></el-table-column>
      <el-table-column prop="barCode" label="商品条码" align="center"></el-table-column>
      <el-table-column prop="goodsName" label="商品" align="center" width="200"></el-table-column>
      <!-- <el-table-column
        prop="dateInProduced"
        label="生产日期"
        align="center"
        key="1"
        v-if="canCancel==false"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.isBatch === '1'">{{scope.row.dateInProduced}}</span>
          <span v-if="scope.row.isBatch === '0'">{{"---"}}</span>
        </template>
      </el-table-column>
      <el-table-column
        prop="goodsBatchNumber"
        label="商品批次"
        align="center"
        key="2"
        v-if="canCancel==false"
      >
        <template slot-scope="scope">
          <span v-if="scope.row.isBatch === '1'">{{scope.row.goodsBatchNumber}}</span>
          <span v-if="scope.row.isBatch === '0'">{{"---"}}</span>
        </template>
      </el-table-column> -->
      <el-table-column prop="unitName" label="单位" align="center"  key="3"></el-table-column>
      <el-table-column prop="goodsSpec" label="规格型号" align="center">
        <template slot-scope="scope">
          <div v-for="(item, index) in scope.row.goodsSpec" :key="index">
            <span>{{item.paramName}} :</span>
            <span>{{item.paramValue}} </span>
          </div>
        </template>
      </el-table-column>
      <el-table-column prop="price" label="单价" align="center" key="5"> </el-table-column>
      <el-table-column prop="goodsNum" label="数量" align="center" key="6" width="150">
        <template slot-scope="scope">
          <span v-show="showTab == '1'">{{scope.row.goodsNum}}</span>
          <input class="commonInput" v-show="showTab == '2'" v-model="scope.row.goodsNum" size="mini" type="text" style="width:100px" value="1" min="0" maxlength="8" oninput="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'')}else{this.value=this.value.replace(/\D/g,'')}" onafterpaste="if(this.value.length==1){this.value=this.value.replace(/[^1-9]/g,'0')}else{this.value=this.value.replace(/\D/g,'')}">
        </template>
      </el-table-column>
      <el-table-column prop="goodsPrice" v-if="canCancel==false"  label="销售价" align="center" key="7"> </el-table-column>
      <el-table-column prop="goodsAmount" label="总价" align="center" v-if="canCancel==true" key="8">
        <template slot-scope="scope">
          <span>{{(scope.row.goodsPrice * scope.row.goodsNum).toFixed(2)}}</span>
        </template>
      </el-table-column>
      <el-table-column prop="confirmNum" label="报货确认数量" align="center"></el-table-column>
      <el-table-column v-if="showTab == '2'" align="center" label="操作" width="180" key="4">
        <template slot-scope="scope">
          <el-button type="text" @click="selectTable.handleSingleDel(scope.$index)" size="mini">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    
    <!-- 费用表单 -->
    <el-form :model="formdata" label-width="120px" size="mini" style="margin-top:25px;">
      <el-row>
        <el-col :span="6">&nbsp;</el-col>
        <el-col :span="6">
          <el-form-item label="操作员：">
            <span v-show="showTab == '1'">{{formdata.userName}}</span>
            <el-input v-show="showTab == '2'" v-model="formdata.userName" disabled></el-input>
          </el-form-item>
          <el-form-item label="备注：">
            <span v-show="showTab == '1'">{{formdata.remark}}</span>
            <el-input v-show="showTab == '2'" v-model="formdata.remark" type="textarea" maxlength="50"></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="6">
          <el-form-item label="总计：">
            <span v-show="showTab == '1'">{{formdata.purchaseAmount}}</span>
            <el-input v-show="showTab == '2'" v-model="formdataTotal" disabled></el-input>
          </el-form-item>
          <el-form-item label="运费：">
            <span v-show="showTab == '1'">{{formdata.freight}}</span>
            <sd-input v-show="showTab == '2'" :val.sync='formdata.freight'></sd-input>
          </el-form-item>
          <el-form-item label="应付总计：">
            <span v-show="showTab == '1'">{{formdata.amount}}</span>
            <el-input v-show="showTab == '2'" v-model="formdataAllTotal" disabled></el-input>
          </el-form-item>
        </el-col>
        <el-col :span="4">
          <el-form-item label="确认商品总计：" prop="priceTotal">
            <el-input v-model="formdata.confirmPurchaseAmount" disabled></el-input>
          </el-form-item>
          <el-form-item label="确认运费：" prop="freight">
            <el-input v-model="formdata.confirmFreight" type="text" disabled></el-input>
          </el-form-item>
          <el-form-item label="确认应付总计：">
            <el-input v-model="formdata.confirmAmount" disabled></el-input>
          </el-form-item>
        </el-col>
      </el-row>
    </el-form>

    <!-- 商品选择弹出框 -->
    <el-dialog title="商品选择" :visible.sync="goodsTable.dialog" :closeOnClickModal='false' :closeOnPressEscape='false'>
      <el-form label-width="0" size="mini">
        <el-form-item>
          <el-button type="primary" @click="handleSelectGoods()">选择</el-button>
          <el-button @click="goodsTable.dialog=false">取消</el-button>
          <el-alert title="未创建价格协议的商品不可选择!" center type="error" :closable="false" style="display:inline;padding:4px 8px;"></el-alert>
        </el-form-item>
        <el-form-item>
          <el-input v-model="selectData.keyword" placeholder="输入商品名称或编号" style="width:200px;">
            <i slot="suffix" class="el-input__icon el-icon-search" @click="goodsTable.handleSearch(_getPurchaseGoodsPage, goodsTable.pageData)"></i>
          </el-input>
        </el-form-item>
      </el-form>
      <el-table :data="goodsTable.tableData" tooltip-effect="dark" @selection-change="goodsTable.handleMultipleSelect" :row-key="goodsTable.getRowKeys">
        <el-table-column type="selection" width="55" :reserve-selection="true"></el-table-column>
        <el-table-column prop="goodsName" label="商品" align="center"></el-table-column>
        <el-table-column prop="unitName" label="单位" align="center"></el-table-column>
        <el-table-column prop="goodsCode" label="商品货号" align="center"></el-table-column>
        <el-table-column prop="barCode" label="商品条码" align="center"></el-table-column>
        <el-table-column prop="supplierName" label="供应商名称" align="center" width="120"></el-table-column>
        <el-table-column prop="parameter" label="规格型号" align="center">
          <template slot-scope="scope">
            <div v-for="(item,index) in scope.row.goodsSpec" :key="index">
              <span v-if="item!=null">{{item.paramName}} :</span>
              <span v-if="item!=null"> {{item.paramValue}} </span>
            </div>
          </template>
        </el-table-column>
        <el-table-column prop="isFreight" label="含运费" align="center" width="170">
          <template slot-scope="scope">
            <span v-show="scope.row.isFreight=='1'">含运费</span>
            <span v-show="scope.row.isFreight=='0'">不含运费</span>
          </template>
        </el-table-column>
        <el-table-column prop="freight" label="运费" align="center" width="170">
        </el-table-column>
        <el-table-column prop="goodsPrice" label="价格" align="center"></el-table-column>
      </el-table>
      <page-unit :pageData="goodsTable.pageData" :func="_getPurchaseGoodsPage"></page-unit>
    </el-dialog>
  </div>
</template>

<script>
import SdInput from "@/components/SdInput";
import pageUnit from "@/components/Page";
import state from "@/util/state";
import util from "@/util";
import { TableHandle } from "@/util/class";
import { mapState } from "vuex";
import {
  getGoodsPurchaseDetails,
  getPurchaseGoodsPage,
  purchaseOrderPay,
  findOrderPriceAgreementListPage,
  selectBaseShopPageList,
  updateGoodsPurchase
} from "@/api";

export default {
  components: { SdInput, pageUnit },

  data () {
    return {
      timestamp: util.timestamp,
      selectData: {
        keyword: ""
      },
      orderStatusArr: state.orderStatusArr,
      id: "",
      showTab: "",
      canClose: false,  // 是否显示关闭单据按钮
      canCancel: false,  // 是否显示取消单据按钮
      canEdit: false,  // 是否显示修改单据按钮
      rules: {
        supplierName: [{ required: true, message: "请选择供应商", trigger: "blur" }],
        receiveDate: [{ required: true, message: "请选择收货时间", trigger: "blur" }]
      },
      formdata: {
        statusFlow: "",
        supplierId: "",
        supplierName: "",
        receiveDate: "",
        orderDate: "",
        purchaseCode: "",
        userName: "",
        remark: "",
        purchaseAmount: 0,
        freight: 0,
        amount: 0,
        confirmPurchaseAmount: 0,
        confirmFreight: 0,
        confirmAmount: 0
      },
      goodsTable: new TableHandle(),  // 商品数组对象
      selectTable: new TableHandle(),  // 选择都商品数组对象
    };
  },

  computed: {
    ...mapState({
      merchantId: state => state.merchantId,
      power: state => state.power,
      userId: state => state.userId,
    }),
    formdataTotal: function () {
      let priceItem = 0,
        freightItem = 0
      this.selectTable.tableData.forEach(i => {
        i.goodsAmount = Number(i.goodsPrice) * Number(i.goodsNum)
        priceItem += i.goodsAmount
        if(Number(i.isFreight) === 0) {
          freightItem +=  Number(i.freight) * Number(i.goodsNum)
        }
      })
      this.formdata.purchaseAmount = isNaN(priceItem) ? 0 : priceItem.toFixed(2)
      this.formdata.freight = isNaN(freightItem) ? 0 : freightItem.toFixed(2)
      return this.formdata.purchaseAmount
    },
    formdataAllTotal: function () {
      return (Number(this.formdata.purchaseAmount) + Number(this.formdata.freight)).toFixed(2)
    }
  },

  created () {
    this.id = util.getQuery().id;
    this.showTab = util.getQuery().showTab;
    if (this.showTab) {
      this.showTab = "1";
    } else {
      this.showTab = "2";
    }
  },

  mounted () {
    this.getDataById()
  },

  methods: {
    tim (row) {
      return state.foryear(parseInt(row.receiveDate));
    },
    
    // 分配权限
    setRole (key) {
      return util.selectTitle(this.power, key)
    },
    
    // 点击批量添加商品
    openGoodsdialog () {
      this.goodsTable.dialog = true
      this._getPurchaseGoodsPage(this.goodsTable.pageData.pageSize, 1)
    },

    getDataById () {
      getGoodsPurchaseDetails({
        id: this.id
      }).then(res => {
        this.formdata = res.data
        this.formdata.receiveDate = util.getdatetime(res.data.receiveDate);  // 收货日期
        this.formdata.orderDate = util.getdatetime(res.data.orderDate);  // 单据日期
        this.selectTable.tableData = res.data.goodsList  // 商品列表
        // 是否显示修改单据按钮
        if(this.formdata.statusFlow == 0 || this.formdata.statusFlow == 2) {
          this.canEdit = true
        }
        // 是否显示关闭单据按钮
        if(this.formdata.statusFlow == 5) {
          this.canClose = true
        }
        // 是否显示取消单据按钮
        if(this.formdata.statusFlow == 0 || this.formdata.statusFlow == 1 || this.formdata.statusFlow == 2 || this.formdata.statusFlow == 3) {
          this.canCancel = true
        }
        let freight = res.data.freight
        this.$nextTick(() => {
          this.formdata.freight = freight
        })
      });
    },

    // 获取商品列表
    _getPurchaseGoodsPage (pageSize, pageNum) {
      getPurchaseGoodsPage({
        shopId: this.merchantId,
        goodsName: this.selectData.keyword,
        pageSize: pageSize,
        pageNum: pageNum,
        status: 0
      }).then(res => {
        res.data.list.forEach(i => i.goodsNum = 0)
         res.data.list.forEach(e=>{
          e.price=e.goodsPrice
        })
        this.goodsTable.tableData = res.data.list
        this.goodsTable.pageData.pageSize = res.data.pageTotal
      });
    },

    // 点击修改
    handleEdit () {
      this.showTab = 2
    },

    submitForm (formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.handleSave()
        } else {
          return false
        }
      });
    },

    // 保存，修改报货订单
    handleSave () {
      // 判断数组不能为空
      if (this.selectTable.tableData.length == 0) {
        this.$message.error("请刷新页面，选择商品")
        return false
      }

      // 判断数量不能小于最小起订数量
      if(this.selectTable.tableData.some(i => i.goodsNum < i.minNum)) {
        this.$message.error("数量不能小于最小起订数量")
        return false
      }

      this.selectTable.tableData.forEach(i => {
        delete i.createTime
        delete i.updateTime
      })

      updateGoodsPurchase({
        id: this.id,
        shopId: this.merchantId,
        supplierId: this.formdata.supplierId,
        supplierName: this.formdata.supplierName,
        receiveDate: this.formdata.receiveDate,
        statusFlow: this.formdata.statusFlow,
        orderDate: this.formdata.orderDate,
        purchaseinCode: this.formdata.purchaseCode,
        remark: this.formdata.remark,
        purchaseAmount: this.formdata.purchaseAmount,
        freight: this.formdata.freight,
        amount: this.formdataAllTotal,
        creator: this.userId,
        goodsList: JSON.stringify(this.selectTable.tableData)
      }).then(res => {
        if (res.code == 200) {
          this.$message.success(res.msg)
          history.back()
        }
      });
    },

    // 关闭/取消单据
    handleOrderDeal (type) {
      this.$delete(this.formdata, "statusFlow")
      this.$set(this.formdata, "statusFlow", type)
      this.handleSave()
    },

    // 点击选择商品
    handleSelectGoods () {
      if (this.goodsTable.isSelect(2, this, '请先选择商品！')) {
        this.goodsTable.multipleSelectTable.forEach(i => {
          i.purchasePriceshow = i.purchasePrice,
          i.purchaseAmount = 0
        })
        this.selectTable.tableData = this.goodsTable.handleMultipleConfirm(this.selectTable.tableData, 'goodsId')
        this.goodsTable.dialog = false
      }
    },
  }
};
</script>

<style lang="less">
.el-input-group__append {
    background-color: #409eff;
    border-color: #409eff;
    color: #ffffff;
}

.el-dialog__header {
  background-color: #25a0e9;
  .el-dialog__title {
    color: #FFFFFF;
  }
  .el-dialog__close {
    color: #FFFFFF;
    &:hover{
      &:before {
        color: #FFFFFF;
      }
    }
  }
}
</style>
